from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.shortcuts import redirect, render


class UserInfo(object):
    def __init__(self, role, name, id):
        self.role = role
        self.name = name
        self.id = id
        self.menu_name = None
        self.text_list = []


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """校验用户是否已经登录"""
        # 1.排除不需要登录就可以访问的 url
        if request.path_info in settings.WL_WRITE_URL:
            return None

        # 2.去 session 中获取用户信息，能获取到正常跳转，否则返回登录界面
        user_dict = request.session.get(settings.WL_SESSION_KEY)

        # 3.未登录则跳转到登录界面
        if not user_dict:
            return redirect(settings.WL_LOGIN_URL)

        # 4.已登录，封装用户信息
        request.wl_user = UserInfo(**user_dict)
        # print(request.wl_user.name)

    def process_view(self, request, callback, callback_args, callback_kwargs):
        """权限管理和菜单默认选中"""

        # 排除不需要登录就可以访问的 url
        if request.path_info in settings.WL_WRITE_URL:
            return None

        # 获取当前用户访问的 url
        current_name = request.resolver_match.url_name

        # 是否是公共的权限
        if current_name in settings.WL_PERMISSION_PUBLIC:
            return

        # 根据用户角色获取自己所具备的权限 （url 路径）
        user_permission_dict = settings.WL_PERMISSION[request.wl_user.role]

        # 获取当前用户访问的 url
        current_name = request.resolver_match.url_name

        # 判断访问的 url 是否在自己具备的权限中
        if current_name not in user_permission_dict:
            # 如果是 ajax 请求，则返回 json 格式的数据
            if request.is_ajax():
                return JsonResponse({'status': False, 'detail': '无权限进行该操作！'})

            # 正常的请求，返回 HTML 页面
            return render(request, 'permission.html')

        # 有权限的话，循环拿到顶级菜单的 name
        text_list = []
        text_list.append(user_permission_dict[current_name]['text'])
        menu_name = current_name
        while user_permission_dict[menu_name]['parent']:
            menu_name = user_permission_dict[menu_name]['parent']
            text = user_permission_dict[menu_name]['text']
            text_list.append(text)

        text_list.append('首页')
        text_list.reverse()

        # 将顶级菜单的 name 添加上 request 中
        request.wl_user.menu_name = menu_name

        # 路径导航
        request.wl_user.text_list = text_list
